package com.company.nuwa.common.utils;

import com.company.nuwa.common.domain.MenuTreeDTO;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>树节点遍历工具类</p>
 *
 * @author Lionel Lee
 * @version 1.0: TreeUtil.java
 * @date 2021/5/25 12:57 下午
 */
@UtilityClass
@Slf4j
public class MenuTreeUtils {
    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public <T extends MenuTreeDTO> List<T> build(List<T> treeNodes, String root) {

        List<T> trees = new ArrayList<>();

        for (T treeNode : treeNodes) {

            if (root.equals(treeNode.getParentMenuId())) {
                log.info("放入根结点");
                trees.add(treeNode);
            }
            log.info("trees:{}", JsonUtils.objectToJson(trees));
            for (T it : treeNodes) {
                if (it.getParentMenuId().equals(treeNode.getMenuId())) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<>());
                    }
                    treeNode.add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public <T extends MenuTreeDTO> List<T> buildByRecursive(List<T> treeNodes, String root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentMenuId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public <T extends MenuTreeDTO> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getMenuId().equals(it.getParentMenuId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
